package com.example.homework9.sqliteroom;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.example.homework9.R;

import java.util.List;

public class SqliteRoomFragment extends Fragment {
    private TextView contentTextView;
    public SqliteRoomFragment() {
        super(R.layout.sqlite_base);
    }

    private void showUsers(List<User> users) {
        StringBuilder stringBuilder = new StringBuilder();
        for (User user:users) {
            stringBuilder.append("id: ").append(user.id)
                    .append("  username: ").append(user.username)
                    .append("  age: ").append(user.age)
                    .append("\n");
        }
        contentTextView.setText(stringBuilder.toString());
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        contentTextView = getView().findViewById(R.id.show);
        EditText nameEditText = getView().findViewById(R.id.edit_name);
        EditText ageEditText = getView().findViewById(R.id.edit_age);
        Button add = getView().findViewById(R.id.add);
        Button query = getView().findViewById(R.id.query);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username;
                int age;
                User user = new User();
                username = nameEditText.getText().toString();
                age = Integer.parseInt(ageEditText.getText().toString());
                user.username = username;
                user.age = age;
                MyRoomDatabase database = MyRoomDatabase.getInstance(getActivity());
                database.userDao().insert(user);
                showUsers(database.userDao().getAll());
                database.close();
            }
        });
        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyRoomDatabase database = MyRoomDatabase.getInstance(getActivity());
                showUsers(database.userDao().searchUsersByAge(18));
            }
        });
    }
}
